const fs = require('fs')
const path = require('path')
const glob = require('glob')
const superagent = require('superagent')
const { resolve, prefix, getToken, isPc } = require('./utils')

module.exports = async () => {
  const token = getToken()
  if (!token) return

  // require('../lib/publish')('all')

  const projDir = resolve()

  if (!fs.existsSync(projDir)) {
    return
  }

  const files = glob.sync(`${projDir}/*.*`)
    .concat(glob.sync(`${projDir}/.!(git|vscode)*`))
    .concat(glob.sync(`${projDir}/src/*.*`))
    .concat(glob.sync(`${projDir}/src/!(admins|components)/**/*.*`))

  const queue = files.map(file => {
    return new Promise((reslove, reject) => {
      fs.readFile(file, (err, data) => {
        if (err) reject(err)
        reslove({
          path: path.relative(projDir, file),
          content: data.toString()
        })
      })
    })
  })

  const filesData = await Promise.all(queue)

  console.info('开始提交文件,请稍后...')
  const res = await superagent
    .post('/GitFile/Commit', {
      loginInput: token,
      codeType: isPc ? 2 : 1,
      files: filesData.filter(data => data.content)
    })
    .use(prefix)


  if (res.body.status !== 1) {
    console.error('提交失败'+res.body.message)
    return
  }

  console.info('文件提交完成,开始检查文件是否完整...')
  const checkRes = await superagent
    .get('/GitFile/Check', { id:res.body.result.id })
    .use(prefix)

    if (res.body.status !== 1) {
      console.error('检查失败'+checkRes.body.message)
      return
    }else{
      console.info(checkRes.body.result)
    }

    require('./publish')('all')
}
